import React, {useState, useEffect, useRef, forwardRef, useImperativeHandle} from 'react';
import {
    Platform,
    StyleSheet, Text,
    TouchableOpacity,View
} from 'react-native';
import * as S from "../Category/styles";
import {getTodayAndSixDaysAgoDate} from "../../utils/utils";
import {useStatisticsEvents} from "../../hooks/useStatisticsEvents";

const dateType = [
    {'key':'DAY','title':'日'},
    {'key':'WEEK','title':'周'},
    {'key':'MONTH','title':'月'},
    {'key':'YEAR','title':'年'},
]

const chartDateType = [
    {'key':'WEEK','title':'周'},
    {'key':'MONTH','title':'月'},
    {'key':'YEAR','title':'年'},
]

const LevelEventsView = forwardRef((props,ref) => {

    const [ selectLevelIndex, setSelectLevelIndex ] = useState(1);
    const [ selectDateType, setSelectDateType ] = useState(dateType[dateType.length-1].key);
    const [ timeSlotIndex, setTimeSlotIndex ] = useState(0);
    const [ startDate, setStartDate ] = useState('');
    const [ endDate, setEndDate ] = useState('');
    const [ timeSlot, setTimeSlot ] = useState([]);
    const [ todayDate, setTodayDate ] = useState('');
    const scrollRef = useRef(null);
    const lock = useRef(false);

    const { loadTimeSlotEvents, timeSlotEvents} = useStatisticsEvents();

    useEffect(()=>{

        if (!lock.current) {
            lock.current = true;
            let today = getTodayAndSixDaysAgoDate().dateTime[1];
            setTodayDate(today);

            loadTimeSlotEvents({
                day: today,
                type: "YEAR",
            }).then(function (response) {
                console.log('-loadTimeSlotEvents-response--',response)
                if (response?.code === 0) {
                    let tmpTimeSlot = response?.data.dates;
                    setStartDate(tmpTimeSlot[tmpTimeSlot.length - 1].startDate);
                    setEndDate(tmpTimeSlot[tmpTimeSlot.length - 1].endDate);
                    setTimeSlot(tmpTimeSlot);
                    if (scrollRef) {
                        setTimeSlotIndex(tmpTimeSlot.length - 1)
                        scrollRef?.current?.scrollToEnd();
                    }
                    loadData('', selectLevelIndex, selectDateType, tmpTimeSlot[tmpTimeSlot.length - 1].startDate, tmpTimeSlot[tmpTimeSlot.length - 1].endDate);
                }
            });
        }

    },[])

    useImperativeHandle(ref,()=>({
        refresh: () => {
            // loadData(selectLevelIndex, selectDateType, startDate, endDate);
        },
    }))

    const getTimeSlot = (day,type) => {
        loadTimeSlotEvents({
            day: day,
            type: type,
        }).then(function (response) {
            console.log('-getTimeSlot-response--',response)
            if (response?.code === 0) {
                let tmpTimeSlot = response?.data.dates;
                setStartDate(tmpTimeSlot[tmpTimeSlot.length - 1].startDate);
                setEndDate(tmpTimeSlot[tmpTimeSlot.length - 1].endDate);
                setTimeSlot(tmpTimeSlot);
                if (scrollRef) {
                    setTimeout(()=>{
                        setTimeSlotIndex(tmpTimeSlot.length - 1)
                        scrollRef?.current?.scrollToEnd();
                    },10)
                }
                loadData('', selectLevelIndex, type, tmpTimeSlot[tmpTimeSlot.length - 1].startDate, tmpTimeSlot[tmpTimeSlot.length - 1].endDate);
            }
        });
    }

    const setDateType = (type) => {
        props.periodCallback && props.periodCallback(false);
        setSelectDateType(type);
        getTimeSlot(todayDate,type);
    }

    const clickTimeSlot = (item, index) => {
        setTimeSlotIndex(index);
        setStartDate(item?.startDate);
        setEndDate(item?.endDate);
        props.periodCallback && props.periodCallback(false);
        loadData('',  selectLevelIndex, selectDateType, item?.startDate, item?.endDate);
    }

    const loadData = (parentId, level,dateType, startDateParam, endDateParam) => {
        props?.loadCallback&&props.loadCallback(parentId,level,dateType,startDateParam,endDateParam);
    }

    const clickPeriodDate = () => {
        setSelectDateType('');
        props?.clickPeriodDate&&props.clickPeriodDate();
    }

    console.log('-====levelevents==state==',timeSlotEvents,'timeSlotIndex:',timeSlotIndex,'startDate:',startDate,'endDate:',endDate)

    return (
        <View style = {styles.levelOne}>
            <View style = {[styles.levelOneMid,{marginBottom: selectDateType ? 0 : 16}]}>
                <View style={[styles.levelOneDateView,{width: props?.from === 'eventsChart' ? '48%':'64%'}]}>
                    {
                        (props?.from === 'eventsChart' ? chartDateType : dateType).map((item)=>{
                            return (
                                <TouchableOpacity
                                    key={'date_'+item.key}
                                    style={[
                                        styles.levelOneDateButton,
                                        {
                                            backgroundColor: selectDateType === item.key ? '#fff' : 'rgba(232, 232, 232, 1)',
                                            width: props?.from === 'eventsChart' ? '33%' : '25%',
                                        }]}
                                    onPress={() => setDateType(item.key)}
                                >
                                    <Text style={[styles.topLevelText,{fontWeight: selectDateType === item.key ? 'bold' : 'normal'}]}>{item.title}</Text>
                                </TouchableOpacity>
                            )
                        })
                    }
                </View>
                <TouchableOpacity
                    style={[styles.levelDateTimeButton,{backgroundColor: props.selectPeriod?'#fff':'rgba(232, 232, 232, 1)'}]}
                    onPress={clickPeriodDate}>
                    {
                        props?.dateTimeWithoutYear?.length > 0 ? <Text style={styles.topLevelText}>{props?.dateTimeWithoutYear.join('-')}</Text> : null
                    }
                </TouchableOpacity>
            </View>

            {
                selectDateType ?
                    <S.Container4
                        ref={scrollRef}
                        horizontal
                        showsHorizontalScrollIndicator={false}
                    >
                        <S.Buttons2Wrapper>
                            {timeSlot.map((item,index) => {
                                return (
                                    <TouchableOpacity
                                        key={'timeSlot_'+index}
                                        style={styles.levelTimeButton}
                                        onPress={() => clickTimeSlot(item,index)}
                                    >
                                        <Text style={[{fontFamily: 'HarmonyOS Sans SC',color: timeSlotIndex === index ? 'rgba(48, 118, 217, 1)' : 'rgba(142, 142, 147, 1)',fontSize: 14}]}>
                                            {item?.name}
                                        </Text>
                                    </TouchableOpacity>
                                );
                            })}
                        </S.Buttons2Wrapper>
                    </S.Container4>:null
            }
        </View>
    )
});

export default LevelEventsView;

const styles = StyleSheet.create({
    levelOne: {
        marginHorizontal: 18,
    },
    levelOneTop: {
        backgroundColor: 'rgba(232, 232, 232, 1)',
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 8,
        marginBottom: 12,
        height: 36,
        borderRadius: 12,
        paddingHorizontal: 2,
        justifyContent: 'space-between',
    },
    levelOneButton: {
        width: '30%',
        height: 32,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 10,
    },
    levelOneMid: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
    },
    levelOneDateView: {
        backgroundColor: 'rgba(232, 232, 232, 1)',
        flexDirection: 'row',
        alignItems: 'center',
        height: 36,
        borderRadius: 12,
        paddingHorizontal: 2,
        width: '64%',
    },
    levelOneDateButton: {
        width: '25%',
        height: 32,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 10,
    },
    levelDateTimeButton: {
        width: '32%',
        backgroundColor: 'rgba(232, 232, 232, 1)',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        height: 36,
        borderRadius: 12,
    },
    levelOneBottom: {

    },
    levelTimeButton: {
        height: 28,
        alignItems: 'center',
        justifyContent: 'center',
        marginRight: 20,
    },
    topLevelText: {
        color: 'rgba(44, 44, 46, 1)',
        fontSize: 14,
        fontFamily: 'HarmonyOS_Sans_SC_Bold'
    },
});
